package com.app.teadoor.home;

import android.os.Build;
import android.os.Bundle;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.app.teadoor.R;
import com.app.teadoor.basis.Constants;
import com.app.teadoor.bean.BasePostData;
import com.app.teadoor.bean.BasisBean;
import com.app.teadoor.bean.ErrorData;
import com.app.teadoor.bean.LoginBean;
import com.app.teadoor.bean.TypeInfoData;
import com.app.teadoor.bean.WorkListBean;
import com.app.teadoor.bean.WorkListData;
import com.app.teadoor.util.MyUtils;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.com.example.rfid.driver.Driver;
import cn.com.example.rfid.driver.RfidDriver;
import cn.pedant.SweetAlert.SweetAlertDialog;
import my.DialogUtils;
import my.LogUtil;
import my.TimeUtils;
import my.http.MyHttpListener;
import my.http.MyHttpUtils;
import my.http.MyParams;

/**
 * 扫描首页
 */
public class HomeIndexActivity extends HomeBaseActivity {

    public final String TAG = "HomeIndexActivity";
    private static final int TIME = 5 * 1000;

    @BindView(R.id.recyclerview_error)
    RecyclerView recyclerview_error;
    private MyErrorAdapter mErrorAdapter;
    private List<ErrorData> errorList;


    @BindView(R.id.text_name)
    TextView text_name;

    @BindView(R.id.text_total)
    TextView text_total;

    private List<String> submitListBean;

    private MyOrderAdapter mOrderAdapter;
    @BindView(R.id.recyclerview_order)
    RecyclerView recyclerview_order;
//    private WorkListBean workListBean;

    private CountDownTimer mHttpTimer;
    private CountDownTimer mWarnTimer;
    private CountDownTimer mSuccessTimer;

    Driver driver;
    Handler handler;

    public String userName;

    @Override
    public void initViews() {
        super.initViews();
        setContentView(R.layout.home_index_activity);
        submitListBean = new ArrayList<>();
        errorList = new ArrayList<>();
        LinearLayoutManager layoutManagerLeft = new LinearLayoutManager(mContext);
        layoutManagerLeft.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerview_error.setLayoutManager(layoutManagerLeft);

        LinearLayoutManager layoutManagerRight = new LinearLayoutManager(mContext);
        layoutManagerRight.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerview_order.setLayoutManager(layoutManagerRight);

        mHttpTimer = new CountDownTimer(TIME, 1000) {
            @Override
            public void onTick(long l) {
                LogUtil.i(TAG, "time---onTick-》" + l);
            }

            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onFinish() {
                LogUtil.i(TAG, "time---onFinish-》");
                noAllOut();
            }
        };

        mWarnTimer = new CountDownTimer(TIME, 1000) {
            @Override
            public void onTick(long l) {
                LogUtil.i(TAG, "mWarnTimer---onTick-》" + l);
                showToast("请退出通道，重新审核!");
            }

            @Override
            public void onFinish() {
                LogUtil.i(TAG, "mWarnTimer---onFinish-》");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        driver.SetGPIOStatus(0x0800, 0x0000, 0);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                needLoop = true;
                                new TagThread().start();
                            }
                        });
                    }
                }).start();

            }
        };

        mSuccessTimer = new CountDownTimer(TIME, 1000) {
            @Override
            public void onTick(long l) {
                LogUtil.i(TAG, "mSuccessTimer---onTick-》" + l);
            }

            @Override
            public void onFinish() {
                LogUtil.i(TAG, "mSuccessTimer---onFinish-》");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        driver.SetGPIOStatus(0x0400, 0x0000, 0);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                needLoop = true;
                                new TagThread().start();
                            }
                        });
                    }
                }).start();

            }
        };


        driver = new RfidDriver();
        driver.Net_Init("192.168.1.10", 20108);
        driver.readMore(0);
        driver.SetGPIOStatus(0x0800, 0x0000, 0);
        handler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what){
                    case 0:
                        text_name.setText(userName);
                        setErrorListView();
                        break;
                    case 1:
                        setOderListView();
                        break;
                }
            }
        };
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        setTitle("鼎白1号半成品仓");

        setErrorListView();
        new TagThread().start();
    }



    @RequiresApi(api = Build.VERSION_CODES.O)
    private void noAllOut(){
        showLoading();
        MyParams params = new MyParams();
        params.put("aid",LoginBean.getInstance().getAcode());

//        params.put("rfids",Arrays.toString(getResources().getStringArray(R.array.rfid_list)).replace("[","").replace("]",""));

        String ss = String.join(",", submitListBean);
//
        params.put("rfids",ss);
        params.put("erfid",text_name.getText().toString());

        MyHttpUtils.post(Constants.URL_WORK_GET_WORKS_IN_OUT, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        if(isFinishing()) return;
                        setWarming(1);
                        showToast("成功");
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
                        if(isFinishing()) return;
//                        super.onFailure(httpWhat, result);
                        BasisBean basisBean = (BasisBean) result;
                        if(basisBean != null&& !TextUtils.isEmpty(basisBean.getCode())&& !basisBean.getCode().equals("500")){
                            try {
                                DialogUtils.showErrorDialog(mContext,basisBean.getStatusInfo());
                                setWarming(0);
                                ErrorData errorData = new ErrorData();
                                errorData.setInfo(basisBean.getStatusInfo().trim());
                                errorData.setTime(TimeUtils.getCurrentTimeByFormat("yyyy-MM-dd HH:mm:ss"));
                                if(errorList.size()>100){
                                    errorList.clear();
                                }
                                errorList.add(0,errorData);
                                setErrorListView();
                            }catch (Exception e){
                                setWarming(0);
                                throw e;
                            }

                        }

                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        dismissProgress();
//                        needLoop = true;
//                        new TagThread().start();
                    }
                },0, WorkListBean.class);

    }




    private void setWarming(int status){

        switch (status){
            case 0:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        driver.SetGPIOStatus(0x0800, 0x0800, 0);  //警告
                    }
                }).start();

                mWarnTimer.start();

                break;
            case 1:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        driver.SetGPIOStatus(0x0400, 0x0400, 0);  //可能是绿灯
                    }
                }).start();
                mSuccessTimer.start();

                break;
        }


    }


    private void setErrorListView() {
        if (mErrorAdapter == null) {
            mErrorAdapter = new MyErrorAdapter();
            recyclerview_error.setAdapter(mErrorAdapter);
        } else {
            mErrorAdapter.notifyDataSetChanged();
        }
    }

    private void setOderListView() {
        if (mOrderAdapter == null) {
            mOrderAdapter = new MyOrderAdapter();
            recyclerview_order.setAdapter(mOrderAdapter);
        } else {
            mOrderAdapter.notifyDataSetChanged();
        }
        text_total.setText("共"+submitListBean.size()+"件");
    }



    public class MyErrorAdapter extends RecyclerView.Adapter<MyErrorAdapter.ViewHolder> {



        //创建新View，被LayoutManager所调用
        @Override
        public MyErrorAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.home_index_item, viewGroup, false);
            return new MyErrorAdapter.ViewHolder(view);
        }

        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(MyErrorAdapter.ViewHolder viewHolder, int position) {
            viewHolder.bind(position);
        }

        //获取数据的数量
        @Override
        public int getItemCount() {
            int count = errorList == null ? 0 : errorList.size();
            return count;
        }

        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.text_time)
            TextView text_time;
            @BindView(R.id.text_message)
            TextView text_message;

            public ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
            }

            public void bind(int position) {
                ErrorData  data = errorList.get(position);
                text_time.setText("" + data.getTime());
                text_message.setText("" + data.getInfo());
            }
        }
    }

    public class MyOrderAdapter extends RecyclerView.Adapter<MyOrderAdapter.ViewHolder> {



        //创建新View，被LayoutManager所调用
        @Override
        public MyOrderAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.home_order_item, viewGroup, false);
            return new MyOrderAdapter.ViewHolder(view);
        }

        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(MyOrderAdapter.ViewHolder viewHolder, int position) {
            viewHolder.bind(position);
        }

        //获取数据的数量
        @Override
        public int getItemCount() {
            int count = submitListBean == null ? 0 : submitListBean.size();
            return count;
        }

        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.text_name)
            TextView text_name;
            @BindView(R.id.text_value)
            TextView text_value;

            public ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
            }

            public void bind(int position) {
                String rfid = submitListBean.get(position);
                text_name.setText("" +(position+1));
                text_value.setText("" + rfid);
            }
        }
    }


    private void addEPCToList(String epc) {

        int Hb = 0;
        int Lb = 0;
        int rssi = 0;
        String[] tmp = new String[3];
        HashMap<String, String> temp = new HashMap<>();
        String text = epc.substring(4);
        String len = epc.substring(0, 2);
        int epclen = (Integer.parseInt(len, 16) / 8) * 4;
        tmp[0] = text.substring(epclen, text.length() - 6);
        tmp[1] = text.substring(0, text.length()-6);
        tmp[2] = text.substring(text.length() - 6, text.length() - 2);

        if(4 != tmp[2].length()){
            tmp[2] = "0000";
        } else {
            Hb = Integer.parseInt(tmp[2].substring(0,2), 16);
            Lb = Integer.parseInt(tmp[2].substring(2, 4), 16);
            rssi = ((Hb - 256 + 1) * 256 + (Lb - 256)) / 10;
        }

        LogUtil.d(TAG,"addEPCToList == "+tmp[1]  +"size=="+tmp[1].length());

        if(tmp[1].length()==12){
            userName = tmp[1];

        }else {
            if(!submitListBean.contains(tmp[1])){
                submitListBean.add(tmp[1]);
                handler.sendEmptyMessage(1);
                mHttpTimer.cancel();
                mHttpTimer.start();
            }
        }

    }

    public boolean needLoop = true;
    class TagThread extends Thread {
        private int nullIndex = 0;
        private String lastEpc ="null";

        public TagThread() {

        }

        public void run() {
            while (needLoop) {
                try {
                    String[] strEpc1 = {driver.GetBufData()};
                    String strEpc = strEpc1[0];
                    LogUtil.d(TAG,"strEpc == "+strEpc);
                    LogUtil.d(TAG,"Epc =nullIndex= "+nullIndex);
                    if (!TextUtils.isEmpty(strEpc)) {
                        nullIndex =0;
                        lastEpc = strEpc;
//                       String b = driver.GetAccessControlTriggerPara();
//                        LogUtil.d("???b=="+b);     //这个很慢
                        String first = strEpc.substring(0,5);
                        if (first.equals("Temp:")) {
                            // 温度信息
                            String Strvalue = strEpc.substring(5);
                            int itemp = Integer.parseInt(Strvalue);
                            float  ftemp = itemp;
                            ftemp = ftemp / 100;
                            Strvalue = Float.toString(ftemp);
                        } else {
                            // 读卡信息
//                            Message msg = handler.obtainMessage();
//                            msg.obj = strEpc;
//                            handler.sendMessage(msg);
                            addEPCToList(strEpc);
                        }
                    } else {
                        if(lastEpc.equals("null")){
                            LogUtil.d(TAG,"lastEpc == "+lastEpc);
                            nullIndex++;
                            LogUtil.d(TAG,"nullIndex == "+nullIndex);
                        }
                        if(nullIndex == 3){
                            submitListBean.clear();
                            handler.sendEmptyMessage(1);
                            needLoop = true;
                            userName = "";
                        }
                        if(nullIndex == 50){
                            nullIndex = 4;
                        }
                        lastEpc ="null";
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
    }

    @Override
    protected void onDestroy() {
        if(driver != null){
            driver.stopRead();
            driver.Close_Net();
        }
        super.onDestroy();
    }









//    private void putList(){
//
//        submitListBean.addAll(Arrays.asList(getResources().getStringArray(R.array.rfid_list)));
//
//        if(submitListBean.size()<1){
//            return;
//        }
//        needLoop = false;
//
//        MyParams params = new MyParams();
//        params.put("aid",LoginBean.getInstance().getAcode());
//        params.put("rfids",Arrays.toString(getResources().getStringArray(R.array.rfid_list)).replace("[","").replace("]",""));
//        params.put("erfid",text_name.getText().toString());
//
//        showLoading();
//        MyHttpUtils.post(Constants.URL_WORK_RETURN_MFS_BY_RFID, params, new MyHttpListener() {
//                    @RequiresApi(api = Build.VERSION_CODES.O)
//                    @Override
//                    public void onSuccess(int httpWhat, Object result) {
//                        if(isFinishing()) return;
//                        TypeInfoData typeInfoData = (TypeInfoData) result;
//                        switch (typeInfoData.getMfs()){
//                            //    1：整板      0 ：非整板  领料
//                            case 0:
//                                noAllOut();
//                                break;
//                            case 1:
//                                allOut ();
//                                break;
//                        }
//                    }
//
//                    @Override
//                    public void onFailure(int httpWhat, Object result) {
//                        if(isFinishing()) return;
//                        dismissProgress();
//                        super.onFailure(httpWhat, result);
//                    }
//
//                    @Override
//                    public void onFinish(int httpWhat) {
//                        new TagThread().start();
//                    }
//                },
//                0, TypeInfoData.class);
//
//
//    }
//private void allOut(){
//
//    MyParams params = new MyParams();
//    params.put("aid",LoginBean.getInstance().getAcode());
//    params.put("rfids",Arrays.toString(getResources().getStringArray(R.array.rfid_list)).replace("[","").replace("]",""));
//    params.put("erfid",text_name.getText().toString());
//
//    MyHttpUtils.post(Constants.URL_WORK_UPDATE_BATCH, params, new MyHttpListener() {
//                @Override
//                public void onSuccess(int httpWhat, Object result) {
//                    if(isFinishing()) return;
//                    workListBean = (WorkListBean) result;
//                }
//
//                @Override
//                public void onFailure(int httpWhat, Object result) {
////                        super.onFailure(httpWhat, result);
//                    if(isFinishing()) return;
//                    try {
//                        BasisBean basisBean = (BasisBean) result;
//                        if (basisBean == null) return;
//                        DialogUtils.showErrorDialog(HomeIndexActivity.this, " " + basisBean.getStatusInfo());
//                    }catch (Exception e){
//                        throw e;
//                    }
//                }
//
//                @Override
//                public void onFinish(int httpWhat) {
//                    dismissProgress();
//                }
//            },
//            0, WorkListBean.class);
//
//}

}
